/**
 * Created by Will Bean on 2016/4/24.
 */
import React, {Component} from 'react'
//import fetch from 'isomorphic-fetch'
import CheckboxInput from './CheckboxInput'
import InputWithLabel from './InputWithLabel'
import TextInput from './TextInput'
import TextareaInput from './TextareaInput'
import SelectInput from './SelectInput'
import FileInput from './FileInput'
import ImageWithState from './ImageWithState'

var map;
var myGeo;
var addIndex = 0;//判断是第几个加入的服务
var serviceIdList = [];//服务保存后存入meta

import {myAjax, ROOTURL_MALL} from '../publicAPI/publicAPI'

import style from './addStore.css'

class StoreEditor extends Component {
    constructor() {
        super();
        this.state = {
            storeName: "",
            servicePhone: "",
            storeAddress: "",
            coordinateLon: "",
            coordinateLat: "",
            startHour: "08",
            startMinute: "00",
            endHour: "18",
            endMinute: "00",
            checkbox8: true,
            storeIntroduction: "",
           
            hasBeenMounted: false,  //判断是否已经加载
            delete: false,
          
            serviceList: []
        };
     
    }

    componentWillMount() {
        serviceIdList = [];
        addIndex = 0;

        console.log("将安装", this.props.params.id);

        if (this.props.params.id != "undefine") {
            //    根据参数获取数据

            if (!this.state.hasBeenMounted && this.props.params.id) {
                console.log('set finished');
                this.handleGetInfo();
            }
        }
    }

    componentDidMount() {
        var _this = this;
        map = new BMap.Map("map");
        var marker;
        myGeo = new BMap.Geocoder();
        var point = new BMap.Point(this.state.coordinateLon, this.state.coordinateLat);
        map.centerAndZoom(point, 18);
        map.addOverlay(new BMap.Marker(point));
        function showInfo(e) {
            // map.removeOverlay(marker);
            map.clearOverlays();
            _this.setState({
                coordinateLon: e.point.lng,
                coordinateLat: e.point.lat
            });
            var point = new BMap.Point(e.point.lng, e.point.lat); // 创建点坐标
            marker = new BMap.Marker(point); // 创建标注
            map.addOverlay(marker); // 将标注添加到地图中
        }

        map.addEventListener("click", showInfo);
    }

    handleGetInfo() {
        var url = ROOTURL_MALL + 'kabuy/pickshop/instance.api?id=' + this.props.params.id;
        var _this = this;
        fetch(url, {
            method: "Get"
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> {
                    console.log(data);
                    _this.setState({
                        storeName: data.name,
                        storeAddress: data.loc.split(",")[0],
                        startHour: parseInt(data.tmOpen / 3600000),
                        startMinute: _this.getMinute(data.tmOpen),
                        endHour: parseInt(data.tmClose / 3600000),
                        endMinute: _this.getMinute(data.tmClose),
                      

                        servicePhone: data.meta.phone,
                        
                       
                       
                    });

                   
                })
            }
        });


    }

    encodeGeoHash(latitude, longitude) {
        var BITS = [16, 8, 4, 2, 1];

        var BASE32 =                                               "0123456789bcdefghjkmnpqrstuvwxyz";
        var NEIGHBORS = { right  : { even :  "bc01fg45238967deuvhjyznpkmstqrwx" },
            left   : { even :  "238967debc01fg45kmstqrwxuvhjyznp" },
            top    : { even :  "p0r21436x8zb9dcf5h7kjnmqesgutwvy" },
            bottom : { even :  "14365h7k9dcfesgujnmqp0r2twvyx8zb" } };
        var BORDERS   = { right  : { even : "bcfguvyz" },
            left   : { even : "0145hjnp" },
            top    : { even : "prxz" },
            bottom : { even : "028b" } };
        var is_even = 1;
        var i = 0;
        var lat = [];
        var lon = [];
        var bit = 0;
        var ch = 0;
        var precision = 12;
        var geohash = "";

        lat[0] = -90.0;
        lat[1] = 90.0;
        lon[0] = -180.0;
        lon[1] = 180.0;

        while (geohash.length < precision) {
            if (is_even) {
                var mid = (lon[0] + lon[1]) / 2;
                if (longitude > mid) {
                    ch |= BITS[bit];
                    lon[0] = mid;
                } else
                    lon[1] = mid;
            } else {
                var mid = (lat[0] + lat[1]) / 2;
                if (latitude > mid) {
                    ch |= BITS[bit];
                    lat[0] = mid;
                } else
                    lat[1] = mid;
            }

            is_even = !is_even;
            if (bit < 4)
                bit++;
            else {
                geohash += BASE32[ch];
                bit = 0;
                ch = 0;
            }
        }
        return geohash;
    }
    getMinute(hour) {
        var m = parseInt((hour - parseInt(parseInt(hour / 3600000) * 3600000)) / 60000);
        var fm = m + '';
        if (m < 10) {
            fm = "0" + m;
        }
        return fm;
    }

    handlerLocationChange() {
        var _this = this;
        myGeo.getPoint(this.state.storeAddress, function (point) {
            if (point) {
                map.centerAndZoom(point, 18);
                map.addOverlay(new BMap.Marker(point));
                _this.setState({
                    coordinateLon: point.lng,
                    coordinateLat: point.lat
                })
            } else {
                alert("您选择地址没有解析到结果!");
            }
        }, "广东省");
    }


    createStore() {
        var meta = {
            phone: this.state.servicePhone,           
            coordinateLon: this.state.coordinateLon,
            coordinateLat: this.state.coordinateLat,
            serviceIdList: serviceIdList
        };
        var data = {
            name: this.state.storeName,
            loc: this.state.storeAddress+","+this.encodeGeoHash(this.state.coordinateLat, this.state.coordinateLon),
            tmOpen: parseInt(this.state.startHour) * 3600000 + parseInt(this.state.startMinute) * 60000,
            tmClose: parseInt(this.state.endHour) * 3600000 + parseInt(this.state.endMinute) * 60000,
            dd:false,
           
            meta: meta
        };
        var _this = this;
        console.log(data)
        var url;
        if (this.props.params.id) {
            url = ROOTURL_MALL + 'kabuy/pickshop/instance.api?id=' + this.props.params.id;
            data.id = this.props.params.id
        } else {
            url = ROOTURL_MALL + 'kabuy/pickshop/instance.api'
        }
        fetch(url, {
            method: 'POST',
            
            body: JSON.stringify(data)
        }).then(function (res) {
        
            if (res.id!="") {
                console.log('保存成功');
                alert('保存成功!');
                location.href = '/MallStoreM';
                // res.json().then(data => {
                    // _this.createAndUpdateService(data.id);
                // })
            } else {
                console.log(res.status)
            }
        }).catch(function (error) {
            console.log('Request failed', error);
        });

    }

    

    handleStoreDelete() {
        var url = ROOTURL_MALL + 'kabuy/pickshop/instance.api?id=' + this.props.params.id;
        this.setState({
            delete: !this.state.delete
        });
        fetch(url, {
            method: 'delete',
            // mode : 'no-cors',
            body: JSON.stringify({})
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> {
                    console.log(data);
                })
            }
        })
    }

  
    getOptions(data) {
        var options = [];
        options.push(data.map((e, index)=><option key={index} value={e}>{e}</option>));
        return options;
    }

    isEmptyObject(e) {
        var t;
        for (t in e)
            return !1;
        return !0
    }


    render() {
        const optionData1 = ["08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"],
            optionData2 = ["00", "05", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55"];
        return (
            <div className="right-wrap">
                <div className="wrap" style={{position:'relative'}}>
                    <div className={style['input_div']}>
                        <label>门店名</label>
                        <TextInput inputId="name" placeHolder="请输入门店名" val={this.state.storeName}
                                   onChange={val=>this.setState({storeName: val})}/>
                    </div>
                    <div className={style['input_div']}>
                        <label>客服电话</label>
                        <TextInput inputId="phone" placeHolder="请输入客服电话" val={this.state.servicePhone}
                                   onChange={val=>this.setState({servicePhone: val})}/>
                    </div>

                    <div className={style['input_div']} id="address">
                        <label>门店地址</label>
                        <TextInput inputId="place" placeHolder="请输入门店地址" val={this.state.storeAddress}
                                   onChange={val=>this.setState({storeAddress: val})}/>
                        <button id="mapSearch" className={style['main_btn']}
                                style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3'} }
                                onClick={this.handlerLocationChange.bind(this)}>查找
                        </button>
                    </div>
                    <div className={style['input_div']}>
                        <label>门店坐标</label>
                        <TextInput inputId="lon" placeHolder="经度" style={{width:"140px"}} val={this.state.coordinateLon}
                                   onChange={val=>this.setState({coordinateLon: val})}/>
                        <TextInput inputId="lat" placeHolder="纬度" style={{width:"140px", marginLeft:"3px"}}
                                   val={this.state.coordinateLat} controlValue={this.state.coordinateLat}
                                   onChange={val=>this.setState({coordinateLat: val})}/>

                    </div>
                    <div className={style['input-div']} style={{display:'none'}}>
                        <label>理发师</label>
                    </div>
                    <div id="map" className={style.map}></div>
                    <div className={style['input_div']}>
                        <label>营业时间</label>
                        <div className={style['dpib']}>
                            <SelectInput id="h1" selectClass={style.tselect} optionsData={this.getOptions(optionData1)}
                                         val={this.state.startHour}
                                         onChange={val=>this.setState({startHour: val})}/>
                            时
                            <SelectInput id="m1" selectClass={style.tselect} optionsData={this.getOptions(optionData2)}
                                         val={this.state.startMinute}
                                         onChange={val=>this.setState({startMinute: val})}/>
                            分——
                            <SelectInput id="h2" selectClass={style.tselect} optionsData={this.getOptions(optionData1)}
                                         val={this.state.endHour}
                                         onChange={val=>this.setState({endHour: val})}/>
                            时
                            <SelectInput id="m2" selectClass={style.tselect} optionsData={this.getOptions(optionData2)}
                                         val={this.state.endMinute}
                                         onChange={val=>this.setState({endMinute: val})}/>
                            分
                        </div>
                    </div>
                  
                  
                  

                    <span id="hint"/>
                    <button id="submit" className={style['main_btn']}
                            style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3'} }
                            onClick={this.createStore.bind(this)}>保存
                    </button>
                    {this.props.params.id ? <button id="delete" className={style['main_btn']}
                                                    style={{backgroundColor: '#f2846f',border: '1px solid #d55c44'} }
                                                    onClick={()=>this.setState({delete: !this.state.delete})}>
                        删除</button> : null}
                    <button id="back" className={style['main_btn']}
                            style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3'} } onClick={()=>history.back()}>返回
                    </button>
                </div>
                
            </div>
        )
    }
}

export default StoreEditor